package com.server.common.utils.wx;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.server.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Classname FengRui
 * @Description 微信先关Api
 * @Date 2022-10-19 16:18
 */
@Slf4j(topic = "WechatUtil")
@Component
public class WechatUtil {

    public static StringRedisTemplate stringRedisTemplate;


    private final static String ACCESS_TOKEN = "ACCESS_TOKEN";
    private static String AppId;
    private static String AppSecret;
    public static String TUrl;

    @Value("${wxConfig.AppId}")
    private void setAppId(String appid) {
        AppId = appid;
    }

    @Value("${wxConfig.AppSecret}")
    private void setAppSecret(String appSecret) {
        AppSecret = appSecret;
    }

    @Value("${wxConfig.tiaozhuang}")
    private void setTUrl(String url) {
        TUrl = url;
    }

    @Resource
    private void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        WechatUtil.stringRedisTemplate = stringRedisTemplate;
    }


    public static JSONObject getWeChatCode(String code) {
        String response = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppId + "&secret=" + AppSecret + "&code=" + code + "&grant_type=authorization_code");
        if (StringUtils.isNotEmpty(response)) {
            return JSON.parseObject(response);
        } else {
            log.error("access_token为空");
            throw new RuntimeException("获取access_token失败");
        }
    }

    public static JSONObject getAccessTokenOauth2(String code) {
        JSONObject weChatCode = getWeChatCode(code);
        if (CollectionUtil.isNotEmpty(weChatCode)) {
            String openid = weChatCode.getString("openid");
            stringRedisTemplate.opsForValue().set(ACCESS_TOKEN + "_" + openid, JSONObject.toJSONString(weChatCode), 110, TimeUnit.MINUTES);
            return weChatCode;
        }
        throw new RuntimeException("获取用户信息失败");
    }

    public static JSONObject getUserInfo(String accessToken, String openId) {
        HttpRequest get = HttpUtil.createGet("https://api.weixin.qq.com/sns/userinfo");
        get.form("access_token", accessToken);
        get.form("openid", openId);
        get.form("lang", "zh_CN");
        String response = get.execute().body();
        if (StringUtils.isNotEmpty(response)) {
            return JSON.parseObject(response);
        } else {
            throw new RuntimeException("获取用户信息失败");
        }
    }
}
